from typing import Optional
from core.database import DatabaseManager
from dao.models import Config


class ConfigDao:
    def __init__(self, db_manager: DatabaseManager):
        self.db_manager = db_manager

    def get(self, key: str):
        session = self.db_manager.get_session()
        try:
            row = session.query(Config).filter(Config.key == key).first()
            if not row:
                return None
            return {
                "key": row.key,
                "value": row.value,
                "desc": row.desc,
                "create_time": row.create_time.isoformat() if row.create_time else None,
                "update_time": row.update_time.isoformat() if row.update_time else None,
            }
        finally:
            session.close()

    def set(self, key: str, value: str, desc: Optional[str] = None):
        session = self.db_manager.get_session()
        try:
            row = session.query(Config).filter(Config.key == key).first()
            if row:
                row.value = value
                row.desc = desc
            else:
                row = Config(key=key, value=value, desc=desc)
                session.add(row)
            session.commit()
        except Exception:
            session.rollback()
            raise
        finally:
            session.close()

    def delete(self, key: str):
        session = self.db_manager.get_session()
        try:
            session.query(Config).filter(Config.key == key).delete()
            session.commit()
        except Exception:
            session.rollback()
            raise
        finally:
            session.close()
